package com.example.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Configuration
@Slf4j
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${captcha.expiration}")
    private Long captchaExpiration;

    // 存储token到Redis
    public void saveToken(String username, String token, long expiration) {
        redisTemplate.opsForValue().set(
                getKey(username),
                token,
                expiration,
                TimeUnit.MILLISECONDS
        );
    }

    // 从Redis获取token
    public String getToken(String username) {
        return (String) redisTemplate.opsForValue().get(getKey(username));
    }

    // 从Redis删除token
    public void deleteToken(String username) {
        redisTemplate.delete(getKey(username));
    }

    // 验证token是否有效
    public boolean validateToken(String username, String token) {
        String storedToken = getToken(username);
        return storedToken != null && storedToken.equals(token);
    }

    // 生成captcha键
    public void setCaptcha(String code, String val) {
        redisTemplate.opsForValue().set(
                getCaptchaKey(code),
                val,
                captchaExpiration,
                TimeUnit.MILLISECONDS
        );
    }

    public String getCaptcha(String uuid) {
        return (String) redisTemplate.opsForValue().get(getCaptchaKey(uuid));
    }

    // 生成Redis键
    private String getKey(String username) {
        return "jwt:" + username;
    }

    // 生成captcha键
    private String getCaptchaKey(String uuid) { return  "captcha:" + uuid; }
}